package com.ruoyi.inducement.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.ImageProcessingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dataAnalysis.domain.InsectType;
import com.ruoyi.inducement.domain.*;
import com.ruoyi.inducement.mapper.InducementMapper;
import com.ruoyi.inducement.service.InducementService;

import com.ruoyi.inducement.utils.ImageInfoTool;
import com.ruoyi.utils.MyDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @program: base-planthopper-detection-master_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2021-09-23 17:31
 **/

@Service
public class InducementServiceImpl implements InducementService {


    @Autowired
    public InducementMapper InducementMapper;

    public ImageInfoTool imageInfoTool;

    /**
     * 插入图片
     * 这里目前先处理一下图片名：diseaseType_shootingTime_meteorological_province_plot_photographer_shootingEquipment.jpg
     * 然后生成图片路径
     * @param InducementLog
     * @return 返回的是图片路径
     */
    @Override
    public InducementLog insertInducementLog(InducementLog InducementLog) throws ImageProcessingException, IOException, ParseException {
        //imageInfoTool =new ImageInfoTool();
        //File file = new File("G:\\学习\\研究生\\code\\基部飞虱检测\\2babb390-53d8-420f-9afb-52e9d17a8345__original.jpg");
        //Date uploadTimeDate=imageInfoTool.ImageShootingTimeDate(file);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");



        //String imageName=InducementLog.getDiseaseType()+"_"+
        //        sdf.format(InducementLog.getShootingTime())+"_"+
        //        InducementLog.getWeather() + "_" +
        //        InducementLog.getWindpower() + "_" +
        //        InducementLog.getTemperature()+ "_" +
        //        InducementLog.getHumidity() + "_" +
        //        InducementLog.getProvince() + "_" +
        //        InducementLog.getCity() + "_" +
        //        InducementLog.getDistrict() + "_" +
        //        InducementLog.getPlot() + "_" +
        //        InducementLog.getphotographer() + "_" +
        //        InducementLog.getShootingEquipment();
        String imageName=InducementLog.getImagePath().split("/")[InducementLog.getImagePath().split("/").length-1];
        imageName=imageName.split("__")[0];
        String ImagePathOld=InducementLog.getImagePath();
        imageName+="__"+ImagePathOld.split("__")[ImagePathOld.split("__").length-1];
        String imagePathOldThum=ImagePathOld.replace("original","thum");
        String imagePathOldResult=ImagePathOld.replace("original","original__Result");
        File oldFile = new File(ImagePathOld);
        File oldFileThum=new File(imagePathOldThum);
        File oldFileResult=new File(imagePathOldResult);

        String path = ImagePathOld.replace(ImagePathOld.split("/")[ImagePathOld.split("/").length-1],"");
        String newImagePath=path+imageName;
        String newImagePathThum=newImagePath.replace("original","thum");
        String newImagePathResult=newImagePath.replace("original","original__Result");
        File newFile = new File(newImagePath);
        File newFileThum=new File(newImagePathThum);
        File newFileResult=new File(newImagePathResult);
        oldFile.renameTo(newFile);
        oldFileThum.renameTo(newFileThum);
        oldFileResult.renameTo(newFileResult);

        newImagePath=newImagePath.replace("\\","/");

        newImagePathThum=newImagePathThum.replace("\\","/");



        //重命名失败，备用手段1，复制该图片，并重命名
        //原因可能是result图片还在被修改，所以有问题
        //检测原因，想要在程序运行中删除图片，他会一直说
        //FileInputStream fin = null;
        //String s=newImagePathResult;
        //FileOutputStream fou = null;
        //byte [] b;
        //int len;

        //b= new byte[1024];
        //fin = new FileInputStream(oldFileResult);
        //fou = new FileOutputStream(s);
        //while((len=fin.read(b)) != -1)
        //{
        //    fou.write(b,0,len);
        //    fou.flush();
        //}
        //fin.close();
        //fou.close();
        //oldFileResult.delete();

        newImagePathResult=newImagePathResult.replace("\\","/");
        InducementLog.setImagePath(newImagePath);
        InducementLog.setThumPath(newImagePathThum);
        InducementLog.setResultPath(newImagePathResult);
        InducementMapper.insertInducementLog(InducementLog);
        return InducementLog;

    }

    /**
     * 查询所有调查信息，图片信息
     * @return
     */
    @Override
    public List<ReturnInducementLog> selectInducementLogAll() {

        return getReturnInfo(InducementMapper.selectInducementLogAll());
    }

    @Override
    public List<ReturnInducementLog> selectInducementLogByConditionMyself(InducementLog InducementLog) {
        return getReturnInfo(InducementMapper.selectInducementLogByConditionMyself(InducementLog));
    }

    /**
     * 分页查询所有调查信息
     */
    @Override
    public TableDataInfo selectInducementLogAllPage(Integer pageNum, Integer pageSize) {
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InducementLog> inducementLogs = InducementMapper.selectInducementLogAll();
        PageInfo<InducementLog> pageInfo = new PageInfo<>(inducementLogs);
        return getTableDataInfo(inducementLogs,pageInfo);

    }



    /**
     * 根据条件查询调查信息（图片信息）
     * @return
     */
    @Override
    public List<ReturnInducementLog> selectInducementLogByCondition(SelectInducementLog selectInducementLog) {
        if(selectInducementLog.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInducementLog.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInducementLog.setEndTime(now.getTime());
        }
        return getReturnInfo(InducementMapper.selectInducementLogByCondition(selectInducementLog));
    }

    /**
     * 根据条件分页查询调查信息（图片信息）
     * @return
     */
    @Override
    public TableDataInfo selectInducementLogByConditionPage(SelectInducementLog selectInducementLog, Integer pageNum, Integer pageSize) {

        if(selectInducementLog.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInducementLog.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInducementLog.setEndTime(now.getTime());
        }
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<InducementLog> inducementLogs = InducementMapper.selectInducementLogByCondition(selectInducementLog);
        PageInfo<InducementLog> pageInfo = new PageInfo<>(inducementLogs);
        return getTableDataInfo(inducementLogs,pageInfo);


    }

    private TableDataInfo getTableDataInfo(List<InducementLog> inducementLogs,PageInfo<InducementLog> pageInfo) {
        List<ReturnInducementLog> returnInfo = getReturnInfo(inducementLogs);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(returnInfo);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    /**
     * 根据条件查询调查人人名
     * @return
     */
    @Override
    public List<String> selectphotographerByCondition(SelectInducementLog selectInducementLog) {
        if(selectInducementLog.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectInducementLog.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectInducementLog.setEndTime(now.getTime());
        }
        return InducementMapper.selectphotographerByCondition(selectInducementLog);
    }

    /**
     * 查询所有的图片信息
     */
    @Override
    public List<String> selectAllImagePath() {
        return InducementMapper.selectAllImagePath();
    }

    /**
     * 手动添加害虫信息
     * @param selectInducementLog
     * @return
     */
    @Override
    public int updateManualTag(SelectInducementLog selectInducementLog) {
        InducementLog InducementLog = new InducementLog();
        InducementLog.setId(selectInducementLog.getId());

        int dm=selectInducementLog.getDm();
        int ehm = selectInducementLog.getEhm();
        int dzjym = selectInducementLog.getDzjym();
        int cdtye = selectInducementLog.getCdtye();


        int other=selectInducementLog.getOther();
        String tagManual="{";
        String otherTag="";
        String cdtyeTag="";
        String dzjymTag="";
        String ehmTag="";
        String dmTag="";
        int flag=0;
        if(other!=0){
            otherTag="\"0\":"+other;
        }
        if(dm!=0){
            dmTag="\"1\":"+ehm;

        }
        if(ehm!=0){
            ehmTag="\"2\":"+ehm;

        }
        if(dzjym!=0){
            dzjymTag="\"3\":"+dzjym;

        }
        if(cdtye!=0){
            cdtyeTag="\"4\":"+cdtye;

        }


        if(!otherTag.equals("")){
            tagManual+=otherTag;
        }
        if(tagManual.length()>3 && (!cdtyeTag.equals("") || !dzjymTag.equals("") || !ehmTag.equals("") || !dmTag.equals(""))){
            tagManual+=",";
        }
        if(!dmTag.equals("")){
            tagManual+=dmTag;
            flag=1;
        }
        if(flag==1 && (!ehmTag.equals("") || !dzjymTag.equals("") ||!cdtyeTag.equals(""))){
            tagManual+=",";
            flag=0;
        }
        if(!ehmTag.equals("") ){
            tagManual+=ehmTag;
            flag=1;
        }
        if(flag==1 && (!dzjymTag.equals("") ||!cdtyeTag.equals(""))){
            tagManual+=",";
            flag=0;
        }
        if(!dzjymTag.equals("") ){
            tagManual+=dzjymTag;
            flag=1;
        }
        if(flag==1 && !cdtyeTag.equals("")){
            tagManual+=",";
        }
        if(!cdtyeTag.equals("") ){
            tagManual+=cdtyeTag;
        }
        tagManual+="}";
        InducementLog.setTagManual(tagManual);
        int count = InducementMapper.updateManualTag(InducementLog);

        return count;
    }

    /**
     * 根据条件返回播报
     * @param selectInducementLog
     * @return
     */
    @Override
    public List<BroadcastInfo> getBroadcastInfo(SelectInducementLog selectInducementLog) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startTime=sdf.format(selectInducementLog.getBeginTime());
        String endTime=sdf.format(selectInducementLog.getEndTime());
        /* 计算时间间隔，按 天 存入 集合 */
        List<String> dates = MyDateUtil.calculateTimeInterval(startTime, endTime);

        /* 存放结果数据集 */
        List<BroadcastInfo> statistics = new ArrayList<>();
        for (String date : dates) {

            Calendar now =Calendar.getInstance();
            now.setTime(sdf.parse(date));
            now.set(Calendar.DATE,now.get(Calendar.DATE)+1);

            selectInducementLog.setBeginTime(sdf.parse(date));
            selectInducementLog.setEndTime(now.getTime());

            List<String> list = InducementMapper.selectTagByCondition(selectInducementLog);
            InsectNumType insectNumType = json2InsectType(list);

            BroadcastInfo insectStatistic = new BroadcastInfo();
            insectStatistic.setInsectNumType(insectNumType);
            insectStatistic.setImgNum(list.size());
            insectStatistic.setDay(date);

            insectStatistic.setInsectTotalNumber(insectNumType.getDm()+insectNumType.getCdtye() + insectNumType.getDzjym() + insectNumType.getEhm() + insectNumType.getOther());
            int average = 0;
            if (insectStatistic.getImgNum() > 0) {
                average = insectStatistic.getInsectTotalNumber() / insectStatistic.getImgNum() * 100;
            }
            insectStatistic.setAverageInsectTotalNumber(average);
            insectStatistic.setLevel(judgmentLevel(average));
            statistics.add(insectStatistic);
        }
        return statistics;
    }


    /**
     * 从数据库的形式加入一个insceptType字段，方便前端获取数据
     * @param inducementLogList
     * @return
     */
    public static List<ReturnInducementLog>  getReturnInfo(List<InducementLog> inducementLogList ){
        List<ReturnInducementLog> returnInducementLogsList = new ArrayList<>();
        for (InducementLog inducementLog : inducementLogList) {
            ReturnInducementLog returnInducementLogs = new ReturnInducementLog();

            returnInducementLogs.setId(inducementLog.getId());
            returnInducementLogs.setImagePath(inducementLog.getImagePath());
            returnInducementLogs.setDiseaseType(inducementLog.getDiseaseType());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            returnInducementLogs.setShootingTime(sdf.format(inducementLog.getShootingTime()));
            returnInducementLogs.setUploadTime(sdf.format(inducementLog.getUploadTime()));
            //returnInducementLogs.setShootingTime(InducementLog.getShootingTime());
            //returnInducementLogs.setUploadTime(InducementLog.getUploadTime());
            returnInducementLogs.setWeather(inducementLog.getWeather());
            returnInducementLogs.setWindpower(inducementLog.getWindpower());
            returnInducementLogs.setTemperature(inducementLog.getTemperature());
            returnInducementLogs.setHumidity(inducementLog.getHumidity());
            returnInducementLogs.setProvince(inducementLog.getProvince());
            returnInducementLogs.setCity(inducementLog.getCity());
            returnInducementLogs.setDistrict(inducementLog.getDistrict());

            returnInducementLogs.setPhotographer(inducementLog.getPhotographer());
            returnInducementLogs.setShootingEquipment(inducementLog.getShootingEquipment());
            if(inducementLog.getTag()==null ||inducementLog.getTag().equals("")){
                inducementLog.setTag("{}");
            }
            returnInducementLogs.setTag(inducementLog.getTag());
            if(inducementLog.getTagManual()==null ||inducementLog.getTagManual().equals("")){
                inducementLog.setTagManual("{}");
            }
            returnInducementLogs.setTagManual(inducementLog.getTagManual());
            returnInducementLogs.setOriginalFileName(inducementLog.getOriginalFileName());
            returnInducementLogs.setThumPath(inducementLog.getThumPath());
            returnInducementLogs.setResultPath(inducementLog.getResultPath());
            returnInducementLogs.setPhone(inducementLog.getPhone());

            //System.out.println(returnInducementLogs.toString());
            InsectNumType insectNumType = json2InsectTypeForOne(returnInducementLogs.getTag());
            returnInducementLogs.setInsectNumType(insectNumType);
            InsectNumType insectTypeManual = json2InsectTypeForOne(returnInducementLogs.getTagManual());
            returnInducementLogs.setInsectNumTypeManual(insectTypeManual);

            returnInducementLogs.setInsectTotalNumber(insectNumType.getDm()+insectNumType.getCdtye() + insectNumType.getDzjym() + insectNumType.getEhm() + insectNumType.getOther());
            int average = 0;

            average = returnInducementLogs.getInsectTotalNumber()  * 100;

            returnInducementLogs.setLevel(judgmentLevel(average));

            returnInducementLogsList.add(returnInducementLogs);
        }
        return returnInducementLogsList;
    }

    /**
     * 判断预警等级 0是最低 4 最高
     *
     * @param quantity 数量
     * @return 等级
     */
    public static int judgmentLevel(Integer quantity) {
        if ((quantity < 1000) && (quantity > 0)) {
            return 1;
        }
        if ((quantity >= 1000) && (quantity < 3000)) {
            return 2;
        }
        if ((quantity >= 3000) && (quantity < 8000)) {
            return 3;
        }
        if (quantity >= 8000) {
            return 4;
        }
        return 0;
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *
     * @param tag tag
     * @return InsectType类型
     */
    public static InsectNumType json2InsectTypeForOne(String tag) {

        int dm=0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int other = 0;

        //System.out.println(tag);
        JSONObject totalNum = JSON.parseObject(tag);
        if (totalNum.containsKey("1")) {
            dm += (Integer) totalNum.get("1");
        }
        if (totalNum.containsKey("2")) {
            ehm += (Integer) totalNum.get("2");
        }
        if (totalNum.containsKey("3")) {
            dzjym += (Integer) totalNum.get("3");
        }
        if (totalNum.containsKey("4")) {
            cdtye += (Integer) totalNum.get("4");
        }

        if (totalNum.containsKey("0")) {
            other += (Integer) totalNum.get("0");
        }

        return new InsectNumType(dm,ehm,dzjym,cdtye, other);
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *
     * @param list list列表
     * @return InsectType类型
     */
    public static InsectNumType json2InsectType(List<String> list) {

        int dm=0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int other = 0;

        for (String s : list) {
            if(s!=null) {
                JSONObject totalNum = JSON.parseObject(s);
                if (totalNum.containsKey("1")) {
                    dm += (Integer) totalNum.get("1");
                }
                if (totalNum.containsKey("2")) {
                    ehm += (Integer) totalNum.get("2");
                }
                if (totalNum.containsKey("3")) {
                    dzjym += (Integer) totalNum.get("3");
                }
                if (totalNum.containsKey("4")) {
                    cdtye += (Integer) totalNum.get("4");
                }

                if (totalNum.containsKey("0")) {
                    other += (Integer) totalNum.get("0");
                }
            }
        }
        return new InsectNumType(dm,ehm,dzjym,cdtye, other);
    }
}
